package com.jozen.smart_toilet_system;

import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.jozen.modelbase.netwoek.Common;
import com.jozen.modelbase.netwoek.base.BaseActivity;
import com.jozen.modelbase.netwoek.base.BaseContract;
import com.jozen.modelbase.netwoek.util.AppUtil;
import com.jozen.modelbase.netwoek.util.JsonUtil;
import com.jozen.modelbase.netwoek.util.MyToastUtil;
import com.jozen.modelbase.netwoek.util.PermissionUtils;
import com.jozen.modelbase.netwoek.util.SpMkvUtils;
import com.jozen.smart_toilet_system.change_ip.IpGetUtil;
import com.jozen.smart_toilet_system.change_ip.ReceiverIP;
import com.jozen.smart_toilet_system.ui.HomeFragment;
import com.jozen.smart_toilet_system.web_socket.BaseCommDataModel;
import com.jozen.smart_toilet_system.web_socket.ChangeIpModel;
import com.jozen.smart_toilet_system.web_socket.ChangeIpResult;
import com.jozen.smart_toilet_system.web_socket.HeartBeat;
import com.jozen.smart_toilet_system.web_socket.MySocketListener;
import com.orhanobut.logger.Logger;
import com.zhangke.websocket.SocketListener;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.response.ErrorResponse;

import java.nio.ByteBuffer;

public class MainActivityNew extends BaseActivity {

    private HomeFragment homeFragment;
    private Fragment currentFragment;

    private HeartBeat heartBeat = new HeartBeat();
    private HeartBeat.ParaDTO dto = new HeartBeat.ParaDTO();
    private ReceiverIP receiverIP;

    @Override
    protected void initView() {
//        init();
        if (homeFragment == null) {
            homeFragment = new HomeFragment();
        }
        receiverIP = new ReceiverIP();
        registerBroadcastReceiver();
        showFragment(homeFragment);
        showInstallTip();
        addSocketListener();
    }


    private void init() {
        PermissionUtils permissionUtils = new PermissionUtils(mContext);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            permissionUtils.getWRPermission();
        } else {
            permissionUtils.permission(0);
            permissionUtils.permission(1);
            permissionUtils.permission(2);
        }
    }


    //升级成功的提示
    private void showInstallTip() {
        int version = SpMkvUtils.decodeInt(Common.KEY_UPDATE);
        int current = AppUtil.getVersionCode();
        if (-1 != version) {
            if (current > version) {
                MyToastUtil.show("升级成功");
                SpMkvUtils.encode(Common.KEY_UPDATE, current);
            }
        } else {
            SpMkvUtils.encode(Common.KEY_UPDATE, current);
        }
    }

    private void registerBroadcastReceiver() {
        try {
            IntentFilter intentFilter = new IntentFilter();
            // for net state changed
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

            if (receiverIP != null) {
                getApplicationContext().registerReceiver(receiverIP, intentFilter);
                setBroadcastReceiverListener();
                Logger.i("registerBroadcastReceiver finished");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setBroadcastReceiverListener() {
        try {
            receiverIP.setIpListener(state -> {
                Log.i("setBroadcastReceiverListener", "getNetState state=" + state);
                if (state > ReceiverIP.NETSTATUS_INAVAILABLE) {
                    String ip = IpGetUtil.getIpAddress(MainActivityNew.this);
                    Log.i("setBroadcastReceiverListener", "修改IP结果为" + ip);
                } else {
                    Log.i("setBroadcastReceiverListener", "没有网络");
                }
            });
        } catch (Exception e) {

        }
    }


    @Override
    protected int getActivityLayoutID() {
        return R.layout.activity_main_new;
    }

    @Override
    protected BaseContract.BasePresenter initPresenter() {
        return null;
    }

    @Override
    public void showSuccess(String message) {

    }

    @Override
    public void showFailed(String message) {

    }


    public final void showFragment(Fragment targetFragment) {
        if (currentFragment == targetFragment)
            return;
        if (targetFragment == null) return;
        FragmentManager mFragmentManager = getSupportFragmentManager();
        if (mFragmentManager != null) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            if (!targetFragment.isAdded()) {
                if (currentFragment == null) {
                    transaction
                            .add(R.id.fl_content, targetFragment);
                } else {
                    transaction
                            .hide(currentFragment)
                            .add(R.id.fl_content, targetFragment);
                }
            } else {
                transaction
                        .hide(currentFragment)
                        .show(targetFragment);
            }
            currentFragment = targetFragment;
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.commitAllowingStateLoss();
        }

    }


    private void removeSocketListener() {
        try {
            if (socketListener != null) {
                WebSocketHandler.getDefault().removeListener(socketListener);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void addSocketListener() {
        try {
            if (socketListener != null) {
                WebSocketHandler.getDefault().addListener(socketListener);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void keepAlive() {
        try {
            BaseApplication.getInstance().getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (heartBeat != null && dto != null) {
                        heartBeat.setFunc("heartBeat");
                        dto.setTime(10);
                        heartBeat.setPara(dto);
                        String actionJson = JsonUtil.toJson(heartBeat);
                        if (!TextUtils.isEmpty(actionJson)) {
                            if (WebSocketHandler.getDefault() != null && WebSocketHandler.getDefault().isConnect()) {
                                WebSocketHandler.getDefault().send(actionJson);
                            }
                        }
                        BaseApplication.getInstance().getHandler().postDelayed(this, 5000);
                    }
                }
            }, 5000);
        } catch (Exception e) {

        }
    }


    private SocketListener socketListener = new MySocketListener() {
        @Override
        public void onConnected() {
            keepAlive();
        }

        @Override
        public void onConnectFailed(Throwable e) {
            try {
                if (e != null) {
                    Log.e("Socket", e.toString());
                } else {
                    Log.e("Socket", "onConnectFailed:null");
                }
                if (BaseApplication.getWebSocketManager() != null) {
                    removeSocketListener();
                    BaseApplication.getWebSocketManager().destroy();
                }
                BaseApplication.getInstance().initWebSocket();
                addSocketListener();
            } catch (Exception exception) {

            }

        }

        @Override
        public void onDisconnect() {
            try {
                Log.e("Socket", "onDisconnect");
                if (WebSocketHandler.getDefault() != null) {
                    WebSocketHandler.getDefault().reconnect();
                }
            } catch (Exception e) {

            }
        }

        @Override
        public <T> void onMessage(String message, T data) {
            try {
                String action = "";
                if (data != null) {
                    action = (String) data;
                    if (!TextUtils.isEmpty(action)) {
                        if (action.equals("doorEvent")) {//二次刷卡开门确认
                            BaseCommDataModel dataModel = JsonUtil.getBeanFromJson(message, BaseCommDataModel.class);
                            if (dataModel != null && dataModel.getPara() != null) {
                                try {
                                    String json = JsonUtil.getJsonFormBean(dataModel.getPara());
                                    BaseCommDataModel.ParaDTO paraDTO = JsonUtil.getBeanFromJson(json, BaseCommDataModel.ParaDTO.class);
                                    if (paraDTO != null) {

                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } else if (action.equals("changeIp")) {//修改设备主机IP
                            BaseCommDataModel dataModel = JsonUtil.getBeanFromJson(message, BaseCommDataModel.class);
                            try {
                                if (dataModel != null && dataModel.getPara() != null) {
                                    String json = JsonUtil.getJsonFormBean(dataModel.getPara());
                                    ChangeIpModel changeIpModel = JsonUtil.getBeanFromJson(json, ChangeIpModel.class);
                                    boolean success = false;
                                    if (changeIpModel != null) {
                                        if (changeIpModel.getEth0() != null) {//网口一
                                            IpGetUtil.mEthIpAddress = changeIpModel.getEth0().getIp() + "";
                                            success = IpGetUtil.setEthernetIP(MainActivityNew.this, "STATIC",
                                                    changeIpModel.getEth0().getIp(),
                                                    changeIpModel.getEth0().getMask(),
                                                    changeIpModel.getEth0().getGateway(),
                                                    changeIpModel.getEth0().getDns1(),
                                                    changeIpModel.getEth0().getDns2());
                                        }

                                        if (changeIpModel.getEth1() != null) {//网口二
                                            IpGetUtil.mEthIpAddress = changeIpModel.getEth1().getIp() + "";
                                            IpGetUtil.setEth2Ip(changeIpModel.getEth1().getIp(), changeIpModel.getEth1().getPrefix());
                                        }
                                        if (success) {
                                            Log.e("Socket", "修改主机IP成功啦~修改之后的当前IP为：《" + IpGetUtil.mEthIpAddress + "》");
                                        } else {
                                            Log.e("Socket", "修改主机IP失败");
                                        }
                                        changeIpResult(success);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else if (action.equals("restartEvent")) {//设备主机重启

                        }
                    }
                }
            } catch (Exception e) {

            }

        }

        @Override
        public void onSendDataError(ErrorResponse errorResponse) {
            super.onSendDataError(errorResponse);
        }

        @Override
        public <T> void onMessage(ByteBuffer bytes, T data) {
            super.onMessage(bytes, data);
        }
    };


    /**
     * 修改IP结果
     *
     * @param flag
     */
    private void changeIpResult(boolean flag) {
        try {
            ChangeIpResult ipResult = new ChangeIpResult();
            ChangeIpResult.ParaDTO paraDTO = new ChangeIpResult.ParaDTO();
            ipResult.setPara(paraDTO);
            ipResult.setFunc("changeIpResult");
            paraDTO.setResult(flag);
            String actionJson = JsonUtil.toJson(ipResult);
            if (!TextUtils.isEmpty(actionJson)) {
                if (WebSocketHandler.getDefault().isConnect()) {
                    WebSocketHandler.getDefault().send(actionJson);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //重启清空城市以及城市ID缓存
        SpMkvUtils.encode(Common.SP_CITY_KEY, "");
        SpMkvUtils.encode(Common.SP_CITY_ID_KEY, "");
    }
}
